package com.xhx.accounting;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;


public class currency_exchange extends Activity {
    private EditText input,output;
    private String currency1,currency2;
    private int displayArea;
    private DecimalFormat decimalFormat;
    public static final String APPKEY = "eac1da657eb9b822";// 你的appkey
    public static final String URL = "https://api.jisuapi.com/exchange/convert";


    private Handler myHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            String json = (String) msg.obj;
            Log.d("myHander", json);
            try {
                JSONObject result = new JSONObject(json);
                if ((int)result.get("status") == 0){
                    Log.d("jsonGet", "0");
                    double camount = (double)((JSONObject)result.get("result")).get("camount");
                    if (displayArea == 2){
                        output.setText(decimalFormat.format(camount));
                    } else if (displayArea == 1){
                        input.setText(decimalFormat.format(camount));
                    }
                } else {
                    Toast.makeText(currency_exchange.this,"Error",Toast.LENGTH_LONG);
                };
            } catch (JSONException e) {
                e.printStackTrace();
                Log.d("JSONObject", "False");
            }
            return false;
        }
    });

    private String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_currency_exchange);

        decimalFormat = new DecimalFormat("0.00");

        Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
        ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this,
                R.array.currency_array, android.R.layout.simple_spinner_item);
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner1.setAdapter(adapter1);

        spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Log.d("spinner","1");
                Log.d("spinnerItem",String.valueOf(parent.getItemAtPosition(position)));
                currency1 = String.valueOf(parent.getItemAtPosition(position));
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent){
            }
        });


        Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);
        ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this,
                R.array.currency_array, android.R.layout.simple_spinner_item);
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner2.setAdapter(adapter2);
        spinner2.setSelection(1);

        spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Log.d("spinner","2");
                Log.d("spinnerItem",String.valueOf(parent.getItemAtPosition(position)));
                currency2 = String.valueOf(parent.getItemAtPosition(position));
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent){
            }
        });

        input = findViewById(R.id.input);
        output = findViewById(R.id.output);
        input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        output.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);

        input.setOnEditorActionListener((v, actionId, event) -> {//设置键盘搜索键和回车的监听
            if (actionId == EditorInfo.IME_ACTION_GO || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {//如果有按下搜索/回车的order
                displayArea = 2;
                String inputText = input.getText().toString().trim();//获得et中的文字
                Convert(currency1,currency2,inputText);
            }
            return false;
        });

        output.setOnEditorActionListener((v, actionId, event) -> {//设置键盘搜索键和回车的监听
            if (actionId == EditorInfo.IME_ACTION_GO || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {//如果有按下搜索/回车的order
                displayArea = 1;
                String inputText = output.getText().toString().trim();//获得et中的文字
                Convert(currency2,currency1,inputText);
            }
            return false;
        });
    }

    private void Convert(String from, String to, String amount){
        url = URL + "?appkey=" + APPKEY + "&from=" + from + "&to=" + to + "&amount=" + amount;
        new convertCurrency().start();
    }

    class convertCurrency extends Thread {
        @Override
        public void run() {

            String jsonStr = null;
            try {
                jsonStr = HttpUtil.sendGet(url, "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (jsonStr != null){
                Message message = new Message();
                message.obj = jsonStr;
                myHandler.sendMessage(message);
            }
        }
    }


    public void onClick(View view) {
        switch (view.getId())
        {
            case R.id.arrow_left:
                finish();
                break;
        }
    }
}